package com.example.nionetty.consumer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author: ZhaoJie
 * @Date: 2022/3/24
 * @Description :
 * @Modify :
 * ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */
public class WebTestPort6666 {
    public static void main(String[] args) throws IOException {

        //创建一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置阻塞模式为非阻塞
        socketChannel.configureBlocking(false);
        //提供服务器端的 ip 和 端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间，客户端不会阻塞，可以做其它工作..");
            }
        }


        //通过定时器发送数据
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    // 连接成功，发送数据
                    String str = "hello, netty！";
                    ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
                    socketChannel.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 1000, 5000);
        System.in.read();
    }
}
